<template>
	<div id="save_contract" v-loading="$store.state.saving"
				element-loading-text="保存中" element-loading-spinner="el-icon-loading"
				element-loading-background = "rgba(255,255,255,0.8)">
		<el-tabs>
			<el-tab-pane label="合同" >
				<el-form
					:model="contract"
					:rules="rules"
					ref="ruleForm"
					label-width="110px"
					style="overflow:hidden">
                    <el-form-item label="合同编号" prop="contractNum">
						<el-input v-model="contract.contractNum" placeholder="可不录，自动生成"></el-input>
					</el-form-item>
					<el-form-item label="合同名称" prop="theme">
						<el-input v-model="contract.theme" placeholder="可不录，自动生成"></el-input>
					</el-form-item>
					<el-form-item label="对应客户" prop="customer.customerId">
						<el-select @change="getOppos()" filterable value-key="customerId" v-model="contract.customer" placeholder="未选" style="width:100%">
							<el-option v-for="item in customers" :key="item.customerId" 
							:label="item.customerName" :value="item"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item  label="对应机会" prop="oppo" class="inline__">
						<el-select v-model="contract.oppo" value-key="oppoId" :disabled="oppos.length == 0" 
							:placeholder="palcehouder" @change="addOppoToContract">
							<el-option v-for="oppo in oppos" 
								:key="oppo.oppoId" 
								:label="oppo.oppoName" 
								:value="oppo"
								></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="总金额" prop="" class="inline__">
						<el-input v-model="total_money" placeholder></el-input>
					</el-form-item>
					<el-form-item  label="分类" prop="" class="inline__">
						<el-select filterable value-key="id" v-model="contract.classify" placeholder="未选">
							<el-option v-for="item in initData.conClassifies" :key="item.id" 
							:label="item.name" :value="item"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="付款方式" prop="" class="inline__">
						<el-select filterable value-key="id" v-model="contract.paymentMethod"  placeholder="未选">
							<el-option v-for="item in initData.paymentMethods" :key="item.id" 
							:label="item.name" :value="item"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="开始结束时间" prop="startTime">
						<el-date-picker
							v-model="contract.startTime"
							type="daterange"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							style="width: 100%;"
						></el-date-picker>
					</el-form-item>
					<el-form-item label="所有者" prop="owner" class="inline__">
						<el-select filterable v-model="contract.owner" value-key="empId">
							<el-option-group v-for="d in  dept_emps" :key="d.departmentId" :label="d.departmentName">
								<el-option v-for="e in d.deEmp" :key="e.empId" :label="e.empName" :value="e"></el-option>
							</el-option-group>
						</el-select>
					</el-form-item>
					<el-form-item label="开票金额" prop="" class="inline__">
						<el-input v-model="contract.invoiceMoney" placeholder></el-input>
					</el-form-item>
					<el-form-item label="客户签约人" prop="" class="inline__">
						<el-input v-model="contract.customerSigner" placeholder="默认为当前客户"></el-input>
					</el-form-item>
					<el-form-item label="我方签约人" prop="" class="inline__">
						<el-select filterable v-model="contract.empSigner" value-key="empId">
							<el-option-group v-for="d in  dept_emps" :key="d.departmentId" :label="d.departmentName">
								<el-option v-for="e in d.deEmp" :key="e.empId" :label="e.empName" :value="e"></el-option>
							</el-option-group>
						</el-select>
					</el-form-item>
					<el-form-item label="签约日期" prop="signTime" class="inline__">
						<el-date-picker v-model="contract.signTime" type="date"
						placeholder="选择日期" style="width: 100%;" format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
					</el-form-item>
					<el-form-item label="结款方式" prop="" class="inline__">
						<el-select filterable value-key="id" v-model="contract.payMethod" placeholder="未选">
							<el-option v-for="item in initData.payMethods" :key="item.id" 
							:label="item.name" :value="item"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="状态" prop="conState" class="inline__">
						<el-select disabled filterable value-key="id" v-model="contract.conState" placeholder="未选">
							<el-option v-for="item in initData.conStates" :key="item.id" 
							:label="item.name" :value="item"></el-option>
						</el-select>
					</el-form-item>
					<!--<el-form-item label="合同文件" prop="">
						<el-input v-model="contract.conFilesUrl" :readonly="true" placeholder style="line-height:38px">
							<el-tag @close="close_tag(file)" type="info" closable slot="prefix" v-for="file in flieList" :key="file.uid">{{ file.name }}</el-tag>

							<el-upload multiple slot="append"  action="upload" :show-file-list="false" :on-success="upload_success">
								<el-button size="small">点击上传文件</el-button>
							</el-upload>

						</el-input>
					</el-form-item> -->
					<el-form-item>
						<el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
						<el-button @click="cancel">取消</el-button>
					</el-form-item>
				</el-form>
			</el-tab-pane>
			<el-tab-pane label="产品">
				<el-table  :data="contract.productList">
					<el-table-column label="图片">
						<template slot-scope="s">
							<el-image :src="s.row.proDetail.proImgSrc" style="width:40px;height:40px;"></el-image>
						</template>
					</el-table-column>
					<el-table-column prop="proDetail.product.productName" label="名称"></el-table-column>
					<el-table-column label="规格属性">
						<template slot-scope="s">
							<span v-for="item in s.row.proDetail.abilities" :key="item.abilityId">{{item.abilityName}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="proDetail.product.productBrand" label="品牌"></el-table-column>
					<el-table-column label="售价" prop="discount">
						<template slot-scope="s">
							<el-input v-model="s.row.discount"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="数量" prop="proCount">
						<template slot-scope="s">
							<el-input type="number" v-model="s.row.proCount"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="金额">
						<template slot-scope="s">
							{{ s.row.discount * s.row.proCount }}
						</template>
					</el-table-column>
					<!--<el-table-column label="操作">
						<template slot-scope="s">
							<el-button size="mini" type="danger" icon="el-icon-delete" circle @click="delete_product(s.row)"></el-button>
						</template>
					</el-table-column>-->
				</el-table>
			</el-tab-pane>
		</el-tabs>
	</div>
</template>
 
<script>
export default {
	name: 'saveContract',
	components:{
		
	},
	data() {
		/* 自定义表单验证 */
		var valiDate = (rule, value, callback) => {
			if (!value || !value[0] || !value[1]) {
				callback(new Error("请选择开始和结束时间"))
			}else{
				callback()
			}
		}
		return {
			initData:{},		// 初始化数据
			customers:[],		// 客户对象
			dept_emps:[],		// 部门员工对象集合
			oppos:[],			// 机会列表
			addProductDialogVisible:false, // 添加产品弹框控制开关
			contract: {			// 合同数据源
				customer:{},
				oppo:{},
				startTime:[new Date(),new Date()],
				overTime:"",
				signTime:new Date(),
				totalMoney:0,
				invoiceMoney:0,
				productList: [],	// 产品数据源
				conState: {			// 合同状态
					id : 1
				},
				empSigner:this.$store.state.user 	// 我方签约人默认为当前登录用户
			},	
			flieList:[],	
			rules: {
				"customer.customerId": [
					{required: true,message: '请选择客户', trigger: 'blur' }
				],
				startTime: [
					{ validator: valiDate,required: true, trigger: 'change,blur' }
				],
				oppo: [
					{ required: true, message: '销售机会', trigger: 'blur' }
				],
				conState: [
					{ required: true, message: '请选择合同状态', trigger: 'blur' }
				]
			}
		};
	},
	methods: {
		/* 删除产品 */
		delete_product(row){
			this.global.confirm("提示","确认删除？",
			() => {
				this.contract.productList.splice(this.contract.productList.indexOf(row),1)
				this.global.mes_success("删除成功")
			},() => {
				this.global.mes_message("取消删除")
			})
		},
		/* 删除文件 */
		close_tag(file){
			this.flieList.splice(this.flieList.indexOf(file),1)
		},
		/* 文件上传成功函数 */
		upload_success(response,file,flie_list){
			this.flieList = flie_list
		},
		/* 从机会添加到合同 */
		addOppoToContract(val){
			this.contract.empSigner = val.worker
			this.contract.customer = val.customer
			val.oppoProList.forEach(p => {
				let obj = {}
				obj.discount = p.offer
				obj.proCount = p.productNum
				obj.proDetail = p.productDetail
				this.contract.productList.push(obj)
			})
		},
		/* 获取初始化数据 */
		getInitData(){
			this.axios.get("api/in-sale/save_init_data")
			.then(res => {
				this.initData = res.data
			})
			.catch(err => {})
			/* 获取客户列表 */
			this.axios.get("api/customer/select_cus")
			.then(res => {
				this.customers = res.data
			})
			.catch()
			/* 获取部门员工列表 */
			this.axios.get("api/dept_emps")
			.then(res => {
				this.dept_emps = res.data
			})
			.catch(
			)
			
		},
		getOppos(){
			/* 获取机会 */
			this.axios.get("api/oppo-sale/oppoNoPage",{params:{"state":2,"customerId":this.contract.customer.customerId}})
			.then(res => {
				this.oppos = res.data
			})
			.catch(err => {
				console.error(err); 
			})
		},
		/* 表单提交 */
		submitForm(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					/* 自动生成合同名称 日期+随机8位数 */
					if(!this.contract.contractNum){
						const now = new Date()
						const month = now.getMonth() + 1
						const day = now.getDate()
						let no =  now.getFullYear()+(month<10? "0"+month:month )+(day<10?"0"+day:day)
						let ran = parseInt(Math.random()*10000000+1,10)
						String.prototype.padLeft =
						Number.prototype.padLeft = function(total, pad) {
							return (Array(total).join(pad || 0) + this).slice(-total);
						}
						const str = ran.padLeft(8)
						const result = no+str
						this.contract.contractNum = result
					}
                    /* 自动生成主题 */
                    if(!this.contract.theme){
                        let theme = "自动生成:"
                        let i = 0
                        if(this.contract.productList.length >0){
                             theme += this.contract.productList[0].proDetail.product.productName
                        }
                        if(this.contract.productList.length >1){
                            theme += "等多件商品的订单"
                        }
                        this.contract.theme = theme
                    }
					/* 客户签约人：不填则默认为当前客户 */
					if(!this.contract.customerSigner){
						this.contract.customerSigner = this.contract.customer.customerName
					}
					/* 处理开始和结速时间 */
					this.contract.overTime = this.contract.startTime[1]
					this.contract.startTime = this.contract.startTime[0]
					/* 处理文件url */
					if (this.flieList){
						let str = ""
						this.flieList.forEach(file => {
							str += file.response + "," 
						})
						this.contract.conFilesUrl = str.substring(0, str.lastIndexOf(","))
					}
					/* 新增请求 */
					this.$store.state.saving = true
					this.axios.post('api/in-sale/contract',this.contract)
					.then(async res => {
						if(!this.contract.contractId){ // 如为新增 才执行修改机会
							this.contract.oppo.state.oppoStateId = 3
							//推进到当前阶段的时间
							this.contract.oppo.nextContactTime = new Date();
							await this.axios.post("api/oppo-sale/saveOppo",this.contract.oppo).then().catch()
						}
						if(this.isOppo){
							this.isOppo.savaContractDialogVisible  = false
                        }else if(this.isDetail){
                            this.isDetail.savaContractDialogVisible = false
                            this.$router.push('/contract-index')
						}else{
							this.$store.state.vueContracte.savaContractDialogVisible = false
							this.$store.state.vueContracte.drawer = false
							this.$store.state.vueContracte.get_conState()
						}
						this.$store.state.saving = false
						this.global.mes_success("合同保存成功")
					})
					.catch(err => {
						this.$store.state.saving = false
						this.global.mes_error("合同保存失败，稍后再试！")
					})
				} else {
					this.global.mes_error("数据校验不通过，请修改后重新提交！")
					return false;
				}
			});
		},
		/* 取消事件：隐藏弹窗 */
		cancel(){
			if(this.isOppo){
				this.isOppo.savaContractDialogVisible = false
            }else if(this.isDetail){
                this.isDetail.savaContractDialogVisible = false
			}else{
				this.$store.state.vueContracte.savaContractDialogVisible = false
			}
			
		}
	},
	created(){
		this.getInitData();
	},
	computed:{
		total_money(){
			let total = 0
			this.contract.productList.forEach(pro => {
				total += pro.proCount * pro.discount
			})
			this.contract.totalMoney = total
			return total
		},
		palcehouder(){
			if(this.oppos.length == 0){
				if (!this.contract.customer){
					return '请先选择客户'
				} else{
					return '当前客户没有销售机会'
				}
			}
		}
	}
}
</script>
<style scoped>
.save_contract_form .el-form-item{width: 100%;margin-bottom: 22px !important;}
.el-select{width: 100%!important;}
.inline__{width:50%!important;display:inline-block}
</style>